package com.yx.backstage.controller;

import com.google.code.kaptcha.Producer;
import com.yx.backstage.config.global.CommonResult;
import com.yx.backstage.model.param.SysUserParam;
import com.yx.backstage.security.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author YangXiong
 */
@Slf4j
@RestController
@RequestMapping("/api")
@Api(tags = "注册登录控制器")
public class LoginController {
    @Resource
    private Producer kaptChaProducer;
    @Resource
    private LoginService loginService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/login")
    @ApiOperation("登录接口")
    public CommonResult<HashMap<String, String>> login(@RequestBody SysUserParam sysUser) {
        log.info("LoginController info login SysUser={}", sysUser);
        return loginService.login(sysUser);
    }

    @GetMapping("/logout")
    @ApiOperation("登出接口")
    public CommonResult<String> logout() {
        log.info("===========>>>>>>logout");
        return loginService.logout();
    }


    /**
     * 获取验证码图片
     */
    @GetMapping("/kaptCha")
    public CommonResult<Map<String, String>> getKaptCha() {
        //生成验证码
        String text = kaptChaProducer.createText();
        String lowerCase = text.toLowerCase();
        //生成图片
        BufferedImage image = kaptChaProducer.createImage(text);
        //将验证码存入redis, 一分钟失效
        String uuid = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(uuid, lowerCase, 1, TimeUnit.MINUTES);

        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        ByteArrayOutputStream outputStream;
        try {
            outputStream =new ByteArrayOutputStream();
            ImageIO.write(image, "png", outputStream);
        } catch (Exception e) {
            log.error("验证码获取失败:" + e.getMessage());
            return CommonResult.fail("验证码获取失败");
        }
        Map<String, String> map = new HashMap<>(2);
        map.put("uuid", uuid);
        map.put("img", encoder.encode(outputStream.toByteArray()));

        return CommonResult.success(map);
    }
}
